package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.verificationsdk.ui.IActivityCallback;
import com.alibaba.verificationsdk.ui.VerifyActivity;
import com.alibaba.verificationsdk.ui.VerifyType;
import com.btex.app.Config;
import com.btex.app.MyApplication;
import com.btex.app.R;
import com.btex.app.RegistActivity;
import com.btex.app.WebActivity;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.LogUtil;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.Util;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wcx on 16/3/16.
 */
public class FragmentLogin extends BaseFragment implements View.OnClickListener {


    private static final java.lang.String TAG = "FragmentLogin";
    private EditText etEmailMobile, etPsw, etIvCode, etGoogleCode;
    private LinearLayout llIvCode;
    private ImageView ivCode;
    private Button btnLogin;
    private TextView tvForgotPsw, tvRegist;
    private boolean isGoogle_code, isIv_code;
    private ImageLoader imageLoader;
    private String token, userName;
    private PreferencesCookieStore cookieStore;
    private MicroAVLIDialog mMicroAVLIDialog;


    private void assignViews() {
        etEmailMobile = (EditText) view.findViewById(R.id.etEmailMobile);
        etPsw = (EditText) view.findViewById(R.id.etPsw);
        llIvCode = (LinearLayout) view.findViewById(R.id.ll_ivCode);
        etIvCode = (EditText) view.findViewById(R.id.et_ivCode);
        ivCode = (ImageView) view.findViewById(R.id.iv_code);
        etGoogleCode = (EditText) view.findViewById(R.id.et_googleCode);
        btnLogin = (Button) view.findViewById(R.id.btnLogin);
        tvForgotPsw = (TextView) view.findViewById(R.id.tvForgotPsw);
        tvRegist = (TextView) view.findViewById(R.id.tvRegist);

        tvForgotPsw.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        ivCode.setOnClickListener(this);
        tvRegist.setOnClickListener(this);
        imageLoader = ImageLoader.getInstance();

        etEmailMobile.addTextChangedListener(new MyWatcher());
        etPsw.addTextChangedListener(new MyWatcher());
        etIvCode.addTextChangedListener(new MyWatcher());
        etGoogleCode.addTextChangedListener(new MyWatcher());

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_login, null);
        assignViews();
        setData();
        mMicroAVLIDialog = new MicroAVLIDialog(getActivity());
        return view;
    }

    @Override
    public void setData() {
        userName = sp.getString(Config.KEY_USER_ACCOUNT, null);
        if (userName != null)
            etEmailMobile.setText(userName);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        Intent i;
        switch (v.getId()) {
            case R.id.btnLogin:

                if (TextUtils.isEmpty(etEmailMobile.getText().toString().trim())) {
                    Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), getString(R.string.input_counter));
//                    SnackbarShow(getString(R.string.input_counter));
                    return;
                }

                if (TextUtils.isEmpty(etPsw.getText().toString().trim())) {
                    Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), getString(R.string.input_psw));
//                    SnackbarShow(getString(R.string.input_psw));
                    return;
                }

                callSDKDoVerification(VerifyType.NOCAPTCHA, null);
//                toLogin(isGoogle_code, isIv_code, "");

                break;

            case R.id.iv_code:

                imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);

                break;
            case R.id.tvRegist:
                i = new Intent(cxt, RegistActivity.class);
                startActivity(i);

//                i = new Intent(cxt, TestActivity.class);
//                startActivity(i);
                break;
            case R.id.tvForgotPsw:
                i = new Intent(cxt, WebActivity.class);
                i.putExtra("web_url", Config.URL + "pub/user_get_password");
                startActivity(i);
                break;

        }
    }

    /**
     * 登录
     *
     * @param google_code true  需要谷歌验证码
     * @param iv_code     true  需要图片验证码
     */
    private void toLogin(boolean google_code, final boolean iv_code, String Verifytoken) {

        mMicroAVLIDialog.show();
        String Engilsh;
        cookieStore = CookieTool.getCookieStore(cxt, sp);
        boolean isEngilsh = sp.getBoolean("isEngilsh", false);

        if (isEngilsh) {
            Engilsh = "en";
        } else {
            Engilsh = "zh_cn";
        }


        final String account = etEmailMobile.getText().toString();
        String psw = etPsw.getText().toString();
        final RequestParams params = new RequestParams();
        params.addHeader("app-version", Config.VERSION);
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        params.addHeader("myclient", "android");
        params.addBodyParameter(Config.KEY_USER_ACCOUNT, account);
        params.addBodyParameter(Config.KEY_USER_PSW, psw);
        params.addBodyParameter("myclient", "android");
        params.addBodyParameter("lang", Engilsh);
        params.addBodyParameter("code_sessionid", Verifytoken);
        params.addBodyParameter("code_scene", "register");

        if (google_code) {
            params.addBodyParameter(Config.KEY_AUTH_NUM, etGoogleCode.getText().toString());
        }
        if (iv_code) {
            params.addBodyParameter(Config.KEY_CHECK_PIC, etIvCode.getText().toString());
        }
        final HttpUtils httpUtils = new HttpUtils();

        httpUtils.configCookieStore(cookieStore);
        httpUtils.configCurrentHttpCacheExpiry(10000);
        httpUtils.send(HttpRequest.HttpMethod.POST, Config.URL_USER_LOGIN, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Log.i("sefwejfwkejw", result);
                mMicroAVLIDialog.dismiss();

                token = cookieStore.getCookie(Config.TOKEN) == null ? null : cookieStore.getCookie(Config.TOKEN).getValue();
                sp.putString(Config.TOKEN, token);
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    if ("1".equals(jsonObj.getString(Config.KEY_CODE))) {
                        etEmailMobile.setText("");
                        etPsw.setText("");
                        etIvCode.setText("");
                        etGoogleCode.setText("");
                        etGoogleCode.setVisibility(View.GONE);
                        llIvCode.setVisibility(View.GONE);
                        isIv_code = false;
                        isGoogle_code = false;
                        mMicroAVLIDialog.dismiss();
//                        new SendPushInfo(sp.getString("baiduID", null), cxt, "baidu");
//                        new SendPushInfo(sp.getString("xiaomiID", null), cxt, "xiaomi");
                        sp.putString(Config.TOKEN, jsonObj.getJSONObject(Config.KEY_DATA).getString(Config.TOKEN));
                        sp.putString(Config.KEY_USER_ACCOUNT, account);
                        sp.putBoolean(Config.KEY_IS_LOGIN, true);
//                        SnackbarShow(getString(R.string.login_suess));
                        EventBus.getDefault().post("loginsuccess");
//                        Intent i = new Intent(cxt, TabsActivity.class);
//                        getActivity().startActivity(i);
//                        getActivity().finish();

                    } else if ("-5".equals(jsonObj.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
//                        SnackbarShow(jsonObj.getString("info"));
                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObj.getString("info"));
                        etGoogleCode.setVisibility(View.VISIBLE);
                        isGoogle_code = true;
                        btnLogin.setBackgroundResource(R.color.bg_gray);
                        btnLogin.setClickable(true);

                    } else if ("-6".equals(jsonObj.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
//                        SnackbarShow(jsonObj.getString("info"));
                        llIvCode.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
                        isIv_code = true;
                        btnLogin.setBackgroundResource(R.color.bg_gray);
                        btnLogin.setClickable(true);
                    } else if ("-1".equals(jsonObj.getString(Config.KEY_CODE))) {
                        btnLogin.setClickable(true);
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(cxt, jsonObj.getJSONObject("info").getString("zh_cn"), Toast.LENGTH_SHORT).show();
//                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
//                        SnackbarShow(jsonObj.getString("info"));
                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObj.getString("info"));
                        if (llIvCode.getVisibility() != View.GONE) {
                            imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
                            etIvCode.setText("");
                        }
                    } else {
                        btnLogin.setClickable(true);
//                        SnackbarShow(jsonObj.getString("info"));
                        Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), jsonObj.getString("info"));
                    }
                } catch (Exception e) {
                    LogUtil.e(TAG, e.toString());
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                LogUtil.e(TAG, "error:" + error + "   msg:" + msg);
            }
        });

    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            if (!TextUtils.isEmpty(etEmailMobile.getText()) && !TextUtils.isEmpty(etPsw.getText())) {
                if (llIvCode.getVisibility() == View.GONE) {
                    if (etGoogleCode.getVisibility() == View.GONE) {
                        btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                        btnLogin.setClickable(true);
                    } else {
                        if (!TextUtils.isEmpty(etGoogleCode.getText())) {
                            btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                            btnLogin.setClickable(true);
                        } else {
                            btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                            btnLogin.setClickable(false);
                        }
                    }
                } else {
                    if (etGoogleCode.getVisibility() == View.GONE) {
                        if (!TextUtils.isEmpty(etIvCode.getText())) {
                            btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                            btnLogin.setClickable(true);
                        } else {
                            btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                            btnLogin.setClickable(false);
                        }
                    } else {
                        if (!TextUtils.isEmpty(etGoogleCode.getText()) && !TextUtils.isEmpty(etIvCode.getText())) {
                            btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                            btnLogin.setClickable(true);
                        } else {
                            btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                            btnLogin.setClickable(false);
                        }
                    }
                }

            } else {
                btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
                btnLogin.setClickable(false);
            }
            if (btnLogin.isClickable()) {
                btnLogin.setTextColor(cxt.getResources().getColor(R.color.white));
            } else {
                btnLogin.setTextColor(cxt.getResources().getColor(R.color.white));
            }
        }
    }


    /**
     * 验签主调用功能函数
     *
     * @param selectedIndex 验证类型，目前只支持 滑动验证
     * @param data          验证需要传入的数据，默认传 null
     */
    public void callSDKDoVerification(VerifyType selectedIndex, String data) {
        if (data == null) {
            VerifyActivity.startSimpleVerifyUI(getActivity(), selectedIndex, "0335", null, new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {


//                    SnackbarShow("请完成安全验证");
                    Util.showSnachBar(getActivity(), getResources().getColor(R.color.red), "请完成安全验证");
                }

                @Override
                public void onResult(int retInt, Map code) {

                    verifyDidFinishedWithResult(retInt, code);
                }
            });
        } else {
            Map<String, String> params = new HashMap<>();
            //设置params，目前只需设置 VerifyActivity.APP_DATA
            params.put(VerifyActivity.APP_DATA, data);
            VerifyActivity.startVerifyUI(getActivity(), params, selectedIndex, "0335", null, new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {


                }

                @Override
                public void onResult(int retInt, Map code) {
                    verifyDidFinishedWithResult(retInt, code);
                }
            });
        }
    }


    /**
     * 验签回调功能函数
     *
     * @param retInt 返回码
     * @param code   返回内容
     */
    public void verifyDidFinishedWithResult(int retInt, Map code) {
        switch (retInt) {
            case VerifyActivity.VERIFY_SUCC:
                mMicroAVLIDialog.dismiss();
                String sessionID = (String) code.get("sessionID");

                toLogin(isGoogle_code, isIv_code, sessionID);

                break;

            case VerifyActivity.VERIFY_FAILED:
                mMicroAVLIDialog.dismiss();

                VerifyActivity.finishVerifyUI();

                break;
        }
    }


}
